﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiTest.Dto.Basic;
using WebApiTest.Dto.System;
using WebApiTest.Dto.Utils;
using WebApiTest.Models;
using WebApiTest.Service.Basic;

namespace WebApiTest.Service.System
{
    public class AccountService
    {
        officeContext db = new officeContext();
        private UserService userService = new UserService();
        private RoleService roleService = new RoleService();

        public JObject loginCheck(JObject request)
        {
            String loginName = request["loginName"].ToString();
            String loginPwd = request["loginPwd"].ToString();
            String randomId = request["randomId"].ToString();
            JObject jObject = new JObject();
            TokenDTO tokenDTO = new TokenDTO();
            OpResultDTO opResult = new OpResultDTO();
            AccountDTO accountDTO = new AccountDTO();
            BasicUser user = userService.loginCheck(loginName);
            if(user == null || !user.LoginPwd.Equals(loginPwd))
            {
                opResult.result = JObject.Parse("{ isLogin: false }");
                jObject.Add("data", JObject.Parse(JsonConvert.SerializeObject(opResult)));
                jObject.Add("message", "用户名或密码错误");
                jObject.Add("status", 401);
            }
            else
            {
                accountDTO.id = user.UserId;
                accountDTO.name = user.UserName;
                accountDTO.roleId = user.RoleId.ToString();
                tokenDTO.accountId = user.UserId;

                accountDTO.token = JWTUtil.DesEncrypt(JsonConvert.SerializeObject(tokenDTO));
                opResult.result = accountDTO;
                jObject.Add("data", JObject.Parse(JsonConvert.SerializeObject(opResult)));
                jObject.Add("message", "");
                jObject.Add("status", 200);
            }
            return jObject;
        }

        public AccountDTO getInfo(String token)
        {
            AccountDTO accountDTO = new AccountDTO();
            long roleId;
            TokenDTO tokenDTO = JWTUtil.verifyToken(token);
            BasicUser user = userService.getByUserId(tokenDTO.accountId);
            roleId = (long)user.RoleId;
            accountDTO.id = user.UserId;
            accountDTO.name = user.UserName;
            accountDTO.username = user.LoginName;
            accountDTO.roleId = user.RoleId.ToString();
            accountDTO.token = JWTUtil.DesEncrypt(JsonConvert.SerializeObject(tokenDTO));
            List<PermissionDTO> listPermissionDto = roleService.listPermissionByRoleId(roleId);
            RoleDTO roleDTO = roleService.getRoleByRoleId(roleId);
            roleDTO.permissions = listPermissionDto;
            accountDTO.role = roleDTO;
            return accountDTO;
        }


    }
}
